<template>
  <my-dialog title=" Assign child to parent" :ok="assign">
    <q-card-section >
      <div class="q-pa-sm row justify-evenly items-center">
        <div>Stock Code:</div>
        <q-select
          v-model="text"
          dense
          class="input-css"
          borderless
          use-input
          :options="scOptions"
          style="width: 250px;"
          @filter="filterFn"
        >
          <template v-slot:no-option>
            <q-item>
              <q-item-section class="text-grey"> No results </q-item-section>
            </q-item>
          </template></q-select
        >
      </div>
      </q-card-section>
  </my-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import {
  assignChildStock,
  getAllLevel5StockCode,
} from 'src/services/stockCodeService';
import { StockItem } from 'src/services/type';
import { useChildMapStore } from 'src/stores/childMapStore';
import { useQuasar } from 'quasar';
import MyDialog from '../container/MyDialog.vue';
const text = ref('');
const strOpts: string[] = [];
const options = ref<string[]>([]);
const scOptions = ref(options);
const lv5List: StockItem[] = [];

const emit = defineEmits(['updateChild']);

const $q = useQuasar();

const useChildMap = useChildMapStore();
const props = defineProps<{
  parent_stock_code: string;
}>();

async function getAllChildData() {
  const res = await getAllLevel5StockCode();
  if (res.data) {
    for (let data of res.data) {
      options.value.push(data.stock_code);
      strOpts.push(data.stock_code);
      lv5List.push(data);
    }
    scOptions.value = options.value;
  }
}

async function assign() {
  const msg = await useChildMap.assignChildStockData(
    props.parent_stock_code,
    text.value
  );

  if (msg.code == 0) {
    $q.notify({
      color: 'negative',
      position: 'bottom',
      message: msg.message,
    });
  } else if (msg.code !== 0) {
    $q.notify({
      color: 'positive',
      position: 'bottom',
      message: 'success',
    });
  }
  emit('updateChild');
}

function filterFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      scOptions.value = strOpts;
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    scOptions.value = options.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}

getAllChildData();
</script>
